package com.example.heimashop.view.activity;

import androidx.fragment.app.Fragment;

import com.example.heimashop.R;
import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.databinding.ActivityMainBinding;
import com.example.heimashop.view.fragment.CartFragment;
import com.example.heimashop.view.fragment.CategoryFragment;
import com.example.heimashop.view.fragment.HomeFragment;
import com.example.heimashop.view.fragment.MineFragment;

/**
 * 主页框架
 * 页面2: MainActivity - 主页框架，包含底部导航
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private HomeFragment homeFragment;
    private CategoryFragment categoryFragment;
    private CartFragment cartFragment;
    private MineFragment mineFragment;
    private Fragment currentFragment;

    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        // 初始化Fragment
        homeFragment = new HomeFragment();
        categoryFragment = new CategoryFragment();
        cartFragment = new CartFragment();
        mineFragment = new MineFragment();

        // 默认显示首页
        currentFragment = homeFragment;
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, homeFragment)
                .commit();
    }

    @Override
    protected void initData() {
        // 主页不需要初始化数据
    }

    @Override
    protected void initListener() {
        binding.bottomNavigation.setOnItemSelectedListener(item -> {
            Fragment targetFragment = null;
            int itemId = item.getItemId();

            if (itemId == R.id.nav_home) {
                targetFragment = homeFragment;
            } else if (itemId == R.id.nav_category) {
                targetFragment = categoryFragment;
            } else if (itemId == R.id.nav_cart) {
                targetFragment = cartFragment;
            } else if (itemId == R.id.nav_mine) {
                targetFragment = mineFragment;
            }

            if (targetFragment != null && targetFragment != currentFragment) {
                switchFragment(targetFragment);
                return true;
            }
            return false;
        });
    }

    private void switchFragment(Fragment targetFragment) {
        if (!targetFragment.isAdded()) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .hide(currentFragment)
                    .add(R.id.fragment_container, targetFragment)
                    .commit();
        } else {
            getSupportFragmentManager()
                    .beginTransaction()
                    .hide(currentFragment)
                    .show(targetFragment)
                    .commit();
        }
        currentFragment = targetFragment;
    }
}
